//
//  UIImageView+URLAnimation.m
//  TeacherNet
//
//  Created by slz on 2017/12/20.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "UIImageView+URLAnimation.h"

static char imageURLKey;

static char _webImageCompletedFilterBlockKey;
static char _tgm_webImage_isSupportAniamtedGIFKey;

@implementation UIImageView (URLAnimation)


- (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

- (void)sd_setImageWithURL:(NSURL *)url {
    [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
}

- (void)sd_setImageWithURL:(NSURL *)url randomPlaceHolder:(BOOL)random {
    UIImage *image = nil;
    if(random) {
        NSArray *colors = [NSArray arrayWithObjects:
                           [UIColor colorWithRGB:0xf2bbb0],
                           [UIColor colorWithRGB:0xc9b6ac],
                           [UIColor colorWithRGB:0xc9bec5],
                           [UIColor colorWithRGB:0x94a69a],
                           [UIColor colorWithRGB:0xf2dcc4],
                           [UIColor colorWithRGB:0x9c8793],
                           nil];
        int index = arc4random()%(colors.count);
        image = [self createImageWithColor:[colors objectAtIndex:index]];
    }
    self.backgroundColor = [UIColor colorWithARGB:0xffffff];
    //    [self sd_setImageWithURL:url placeholderImage:image options:SDWebImageRetryFailed progress:nil completed:nil];
    [self sd_setImageWithURL:url placeholderImage:image options:0 progress:nil completed:nil];
}

- (void)sd_setImageWithURL:(NSURL *)url randomPlaceHolder:(BOOL)random comepletion:(SDExternalCompletionBlock)completion{
    UIImage *image = nil;
    if(random) {
        NSArray *colors = [NSArray arrayWithObjects:
                           [UIColor colorWithRGB:0xf2bbb0],
                           [UIColor colorWithRGB:0xc9b6ac],
                           [UIColor colorWithRGB:0xc9bec5],
                           [UIColor colorWithRGB:0x94a69a],
                           [UIColor colorWithRGB:0xf2dcc4],
                           [UIColor colorWithRGB:0x9c8793],
                           nil];
        int index = arc4random()%(colors.count);
        image = [self createImageWithColor:[colors objectAtIndex:index]];
    }
    self.backgroundColor = [UIColor colorWithARGB:0xffffff];
    //    [self sd_setImageWithURL:url placeholderImage:image options:SDWebImageRetryFailed progress:nil completed:nil];
    [self sd_setImageWithURL:url placeholderImage:image options:0 progress:nil completed:completion];
}


-(void)sd_setImageWithURL:(NSURL *)url randomPlaceHolder:(BOOL)random options:(SDWebImageOptions)options
{
    UIImage *image = nil;
    if(random) {
        NSArray *colors = [NSArray arrayWithObjects:
                           [UIColor colorWithRGB:0xf2bbb0],
                           [UIColor colorWithRGB:0xc9b6ac],
                           [UIColor colorWithRGB:0xc9bec5],
                           [UIColor colorWithRGB:0x94a69a],
                           [UIColor colorWithRGB:0xf2dcc4],
                           [UIColor colorWithRGB:0x9c8793],
                           nil];
        int index = arc4random()%(colors.count);
        image = [self createImageWithColor:[colors objectAtIndex:index]];
    }
    self.backgroundColor = [UIColor colorWithARGB:0xffffff];
    [self sd_setImageWithURL:url placeholderImage:image options:options progress:nil completed:nil];
}

- (void)sd_cancelCurrentImageLoad {
    [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"];
}

- (void)sd_cancelCurrentAnimationImagesLoad {
    [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"];
}

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDExternalCompletionBlock)completedBlock {
    [self sd_cancelCurrentImageLoad];
    objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    //设置placeholder 图片也不支持gif

    if (!(options & SDWebImageDelayPlaceholder)) {
        self.image = placeholder;
    }
    
    if (url) {
        
        __weak UIImageView *wself = self;
        
        id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager loadImageWithURL:url options:options progress:progressBlock completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (!wself) return;
                dispatch_main_async_safe(^{
                if (!wself) return;
                
                UIImage *resultImage = image;
                if (resultImage.images.count) {
                    resultImage = image.images[0];
                }
                
//                TGMWebImageCompletedWithFinishedFilter filter = objc_getAssociatedObject(self, &_webImageCompletedFilterBlockKey);
//                if (filter)
//                {
//                    filter(image, url, error, cacheType, finished);
//                }
                
                if (resultImage) {
                    if (cacheType == SDImageCacheTypeDisk
                        || cacheType == SDImageCacheTypeMemory)
                    {
                        [wself setImage:image animated:NO];
                    }
                    else
                    {
                        [wself setImage:image animated:YES];
                    }
                    [wself setNeedsLayout];
                } else {
                    if ((options & SDWebImageDelayPlaceholder)) {
                        wself.image = placeholder;
                        [wself setNeedsLayout];
                    }
                }
                    if (completedBlock && finished) {
                        completedBlock(image, error, cacheType, url);
                    }
            });
        }];
        [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];

    } else {
        dispatch_main_async_safe(^{
            NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
            if (completedBlock) {
                completedBlock(nil, error, SDImageCacheTypeNone, url);
            }
        });
    }
}




@end
